<template>
  <div class="role-index">
    <a-card>
      <InputGroup @search="Search" @reset="Reset">
        <a-form
          :model="formData"
          :wrapper-col="{ style: { width: '150px' } }"
          layout="inline"
        >
          <a-form-item label="搜索">
            <a-input v-model:value="formData.roleName" allow-clear></a-input>
          </a-form-item>
          <a-form-item label="状态">
            <a-select ref="select" v-model:value="formData.status">
              <a-select-option value="">全部</a-select-option>
              <a-select-option :value="1">正常</a-select-option>
              <a-select-option :value="0">停用</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </InputGroup>

      <a-flex justify="flex-end" style="margin-bottom: 16px">
        <a-space>
          <a-button type="primary" @click="Add">
            <icon type="PlusOutlined" />
            新增角色
          </a-button>
        </a-space>
      </a-flex>

      <Table
        ref="table"
        :config="tableConfig"
        @view="View"
        @edit="Edit"
        @delete="Delete"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.title === '状态'">
            <a-switch
              v-model:checked="record.status"
              :checkedValue="1"
              :unCheckedValue="0"
              @change="Switch(record)"
            />
          </template>
        </template>
      </Table>

      <Dialog :config="dialogConfig" @submit="Submit" @cancel="Cancel">
        <a-spin :spinning="dialogLoading">
          <a-form
            :model="dialogData"
            :disabled="dialogFormDisabled"
            :labelCol="{ span: 4 }"
            :wrapperCol="{ span: 20 }"
          >
            <a-form-item label="角色名称" :roles="[{ required: true }]">
              <a-input v-model:value="dialogData.roleName" />
            </a-form-item>
            <a-form-item label="权限字符">
              <a-input v-model:value="dialogData.roleKey" />
            </a-form-item>
            <a-form-item label="菜单权限">
              <a-tree-select
                v-model:value="dialogData.menuIds"
                style="width: 100%"
                :tree-data="treeData"
                tree-checkable
                allow-clear
                :show-checked-strategy="SHOW_ALL"
                placeholder="请选择菜单"
                tree-node-filter-prop="label"
                :fieldNames="{
                  label: 'menuName',
                  value: 'id',
                  children: 'children',
                }"
                @select="treeSelect"
              />
            </a-form-item>
            <a-form-item label="状态">
              <a-radio-group v-model:value="dialogData.status">
                <a-radio :value="1">正常</a-radio>
                <a-radio :value="0">停用</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-form>
        </a-spin>
      </Dialog>
    </a-card>
  </div>
</template>

<script setup>
import Table from "@/components/Table/index.vue";
import InputGroup from "@/components/InputGroup/index.vue";
import Dialog from "@components/Dialog/index.vue";
import { menusTree } from "@api/system/menu.js";
import { TreeSelect } from "ant-design-vue";
import icon from "@utils/icon";
import { message, Modal } from "ant-design-vue";
import {
  getRoleListPage,
  roleChangeShow,
  roleAdd,
  roleDelete,
  roleEdit,
  getRoleInfoById,
} from "@api/system/role.js";
import { createVNode, ref } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";

const SHOW_ALL = TreeSelect.SHOW_ALL;
const treeData = ref([]);
// 弹窗菜单树
const selectMenuTree = ref([]);
// 表单是否禁用
const dialogFormDisabled = ref(true);
// 弹窗加载数据loading
const dialogLoading = ref(false);
// 是否编辑
const isEdit = ref(false);
// 表格实例
const table = ref(null);
// 搜索数据
const formData = ref({
  roleName: "",
  status: "",
});
// 新增、查看、修改弹窗表单数据
let dialogData = ref({
  roleName: "",
  roleKey: "",
  status: 1,
  menuIds: [],
});
// 表格配置
const tableConfig = reactive({
  url: getRoleListPage,
  columns: [
    {
      key: "roleName",
      title: "角色名称",
      dataIndex: "roleName",
      align: "center",
    },
    {
      key: "roleKey",
      title: "角色标识",
      dataIndex: "roleKey",
      align: "center",
    },
    {
      key: "status",
      title: "状态",
      dataIndex: "status",
      align: "center",
    },
    {
      title: "操作",
      align: "center",
      width: "200px",
    },
  ],
  params: {},
  table: {
    size: "middle",
    bordered: true,
  },
  isPagination: true,
  dataPath: "data.records",
  buttons: {
    view: ["system:role:detail"],
    edit: ["system:role:update"],
    add: [],
    delete: ["system:role:delete"],
    role: [],
  },
});
// 新增、查看、修改弹窗配置
const dialogConfig = reactive({
  open: false,
  title: "添加角色",
  width: "30%",
  okText: "确定",
  cancelText: "取消",
  confirmLoading: false,
  destroyOnClose: true,
});

onMounted(() => {
  loadTreeData();
});

const loadTreeData = async () => {
  const response = await menusTree();
  if (response.code === 200) {
    treeData.value = response.data;
  } else {
    message.error("获取菜单树失败，" + response.message);
  }
};

const handleTreeNode = (data) => {
  const nodeArr = [];
  if (data.pid === null) {
    return;
  } else {
    const node = data.pid;
    nodeArr.push(node);
    handleTreeNode(node);
  }
  return nodeArr;
};

const treeSelect = (value, node, extra) => {
  selectMenuTree.value = handleTreeNode(node);
  selectMenuTree.value.push(value);

  console.log(value);
  console.log(node);
  console.log(selectMenuTree);
};

const Search = () => {
  tableConfig.params = formData.value;
  table.value.loadData();
};
const Reset = () => {
  formData.value = {};
  tableConfig.params = formData.value;
  table.value.loadData();
};

// 表格查看、编辑、删除
const View = async (record) => {
  dialogLoading.value = true;
  dialogConfig.open = true;
  dialogConfig.title = "查看角色";
  dialogFormDisabled.value = true;
  const response = await getRoleInfoById(record.id);
  if (response.code === 200) {
    dialogData.value = response.data;
    selectMenuTree.value = response.data.menuIds;
  } else {
    message.error("获取角色信息失败，" + response.message);
  }
  dialogLoading.value = false;
};
const Add = async () => {
  isEdit.value = false;
  dialogConfig.open = true;
  dialogFormDisabled.value = false;
  dialogConfig.title = "新增角色";
  selectMenuTree.value = [];
};
const Edit = async (record) => {
  dialogLoading.value = true;
  isEdit.value = true;
  dialogConfig.open = true;
  dialogConfig.title = "编辑角色";
  dialogFormDisabled.value = false;
  const response = await getRoleInfoById(record.id);
  if (response.code === 200) {
    dialogData.value = response.data;
    selectMenuTree.value = response.data.menuIds;
  } else {
    message.error("获取角色信息失败，" + response.message);
  }
  dialogLoading.value = false;
};
const Delete = async (record) => {
  // 弹窗确认删除
  Modal.confirm({
    title: "",
    icon: createVNode(ExclamationCircleOutlined),
    content: "是否确认删除该菜单？",
    centered: true,
    async onOk() {
      try {
        const response = await roleDelete([record.id]);
        if (response.code === 200) {
          message.success("删除成功！");
          table.value.loadData();
        } else {
          message.error("删除失败，" + response.message);
        }
      } catch {
        return console.log("errors!");
      }
    },
    onCancel() {},
  });
};
// 表格项状态切换
const Switch = async (record) => {
  const response = await roleChangeShow({
    id: record.id,
  });
  if (response.code === 200) {
    message.success("修改状态成功！");
    table.value.loadData();
  } else {
    message.error("修改状态失败，" + response.message);
    table.value.loadData();
  }
};

// 弹窗表单提交
const Submit = async () => {
  dialogConfig.subLoading = true;
  try {
    const response = isEdit.value
      ? await roleEdit({ ...dialogData.value })
      : await roleAdd({ ...dialogData.value });
    if (response.code === 200) {
      message.success(isEdit.value ? "修改成功！" : "添加成功！");
      dialogConfig.open = false;
      dialogData.value = {
        roleName: "",
        roleKey: "",
        status: 1,
        menuIds: [],
      };
      table.value.loadData();
    } else {
      message.error(
        (isEdit.value ? "修改失败，" : "添加失败，") + response.message,
      );
    }
  } catch (error) {
    message.error("操作失败，请稍后重试。");
  } finally {
    dialogConfig.subLoading = false;
  }
};
// 弹窗表单取消
const Cancel = () => {
  dialogConfig.open = false;
  dialogData.value = {
    roleName: "",
    roleKey: "",
    status: 1,
    menuIds: [],
  };
};

// watch(selectMenuTree, (newVal) => {
//   // console.log(newVal);
//   dialogData.value.menuIds = newVal;
// });
</script>

<style scoped lang="scss"></style>
